package com.wc.shj.intercepter;

import cn.hutool.core.util.StrUtil;
import com.wc.shj.util.JsonUtil;
import com.wc.shj.vo.ResultVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * token校验 登录安全拦截器
 */
@Component
public class TokenAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)) {
            ResultVO<String> jsonObj =
                    ResultVO.failure(500, "token不存在!");
            JsonUtil.toJson(response,jsonObj);
            return false;
        }
        else {
            Object readObj = redisTemplate.opsForValue().get(token);
            if(readObj == null) {
                ResultVO<String> jsonObj =
                        ResultVO.failure(500, "token已过期，请重新登录!");
                JsonUtil.toJson(response,jsonObj);
                return false;
            }
            else {
                Long expire = redisTemplate.getExpire(token, TimeUnit.SECONDS);
                System.out.println("token固定过期时间是：" + expire);
                if(expire < 20) {
                    redisTemplate.opsForValue().set(token,readObj,300,TimeUnit.SECONDS);
                }
                return true;
            }
        }
    }
}
